<template>
  <div class="media-input">
    <h4 class="title">{{ $t('document.title') }}</h4>
    <Tree 
      v-if="treeData.length"
      :value="documentId" 
      :data="treeData" 
      label-props="title" 
      value-props="id"
      @update:value="(params) => updateDocumentId(params)"></Tree>
    <div class="btns">
      <Button @click="emit('close')" style="margin-right: 10px;">{{ $t('document.cancel') }}</Button>
      <Button type="primary" @click="insertDocument()">{{ $t('document.confirm') }}</Button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getWikiTree } from '@/api'
import Button from '@/components/Button.vue'
import Tree from '@/components/Tree.vue'
import { useWikiStore } from '@/store'
import message from '@/utils/message'
import i18next from 'i18next'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'

const { t } = i18next

const treeData = ref([])
const documentId = ref<string>('')
const type = ref<string>('')
const emit = defineEmits<{
  (event: 'insertDocument', url: string, value: string): void
  (event: 'close'): void
}>()

const wikiStore = useWikiStore()
const { wikiId} = storeToRefs(wikiStore)

// 插入文档
const insertDocument = () => {
  if (!documentId.value) return message.error(t('document.title'))
  emit('insertDocument', `${import.meta.env.VITE_BASE_URL}/pptlink/document/` + documentId.value + '/' + type.value, documentId.value)
}

// 更新domId,和string
const updateDocumentId = (params: {value: string, type: string}) => {
  documentId.value = params.value
  type.value = params.type
}

const justFun = (node: any) => {
  return node.type !== 'ppt'
}

const filterTree = (treeData:any, condition: (args:any) => any) => {  
  return treeData.reduce((acc:any, node: any) => {
    if (condition(node)) {
      acc.push({
        ...node,
        children: filterTree(node.children, condition)
      })
    }
    return acc
  }, [])
}

onMounted(() => { 
  getWikiTree(wikiId.value as string).then(res => {
    treeData.value = filterTree(res.data, justFun) 
  }).catch(e => {

  })
})

</script>

<style lang="scss" scoped>
.media-input {
  width: 480px;
}
.title{
  font-size: 16px;
  margin: 10px 0;
}
.btns {
  margin-top: 10px;
  text-align: right;
}
</style>
